// g++ socket_srv.cpp -lwsock32 -o socket_srv
//#include "stdafx.h"
#include<stdio.h>
#include<tchar.h>
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
using namespace std;

#pragma pack(4)
typedef struct machine_cmd{
uint32_t en;
double x;
double y;
double z;
} ;
#pragma pack()
typedef union u_cmd{
machine_cmd mc;
char raw[28];
};
 
// #pragma comment(lib, "ws2_32.lib")
int main(int argc, _TCHAR* argv[])
{
    u_cmd mc_out;
    mc_out.mc.x =1.0;
    mc_out.mc.y = 2.2;
    mc_out.mc.z = 50;
    mc_out.mc.en = 24;




    WSAData wsd;           //初始化信息
    SOCKET soSend;         //发送SOCKET
    int nRet = 0;
    //int i = 0;
    int dwSendSize = 0;
    SOCKADDR_IN siLocal;    //远程发送机地址和本机接收机地址
 
    //启动Winsock
    if (WSAStartup(MAKEWORD(2,2),&wsd) != 0) {/*进行WinSocket的初始化,
        windows 初始化socket网络库，申请2，2的版本，windows socket编程必须先初始化。*/
        cout << "WSAStartup Error = " << WSAGetLastError() << endl;
        return 0;
    }
 
    //创建socket
 
    //AF_INET 协议族:决定了要用ipv4地址（32位的）与端口号（16位的）的组合
    //SOCK_DGRAM --  UDP类型，不保证数据接收的顺序，非可靠连接；
    soSend = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
    if (soSend == SOCKET_ERROR) {
        cout << "socket Error = " << WSAGetLastError() << endl;
        return 1;
    }
 
    //设置端口号
    // int nPort = 5150;
    int nPort = 50000;

    siLocal.sin_family = AF_INET;
    siLocal.sin_port = htons(nPort);
    siLocal.sin_addr.s_addr = inet_addr("192.168.50.216");
    // siLocal.sin_addr.s_addr = inet_addr("127.0.0.1");

    for (int i = 0; i < 30; i ++){
        //开始发送数据
        //发送数据到指定的IP地址和端口
        nRet = sendto(soSend,mc_out.raw,28,0,(SOCKADDR*)&siLocal,sizeof(SOCKADDR));
        if (nRet == SOCKET_ERROR) {
            cout << "sendto Error " << WSAGetLastError() << endl;
            break;
        }
    }
    //关闭socket连接
    closesocket(soSend);
    //清理
    WSACleanup();
 
    return 0;
}

